package org.farm.product.domain.chain.handler;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.farm.common.response.enums.BusinessException;
import org.farm.common.response.enums.ResultCodeEnums;
import org.farm.product.domain.bo.ProductSpuBo;
import org.farm.product.domain.convert.ProductSpuBoConvert;
import org.farm.product.infra.basic.entity.ProductSpu;
import org.farm.product.infra.basic.service.ProductSpuService;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Objects;


/**
 * @author Frank Zou
 * @version v0.0.1
 * @date 2025/4/22
 * @description
 */
@Slf4j
@Order(1)
@Component
public class ProductSpuBasicHandler implements ProductSpuHandler {

    private final ProductSpuService productSpuService;

    private ProductSpuHandler nextHandler;

    public ProductSpuBasicHandler(ProductSpuService productSpuService) {
        this.productSpuService = productSpuService;
    }


    @Override
    public void handler(ProductSpuBo productSpuBo) {
        productSpuBo.setId(IdWorker.getId());
        ProductSpu productSpu = ProductSpuBoConvert.INSTANCE.convertBoToEntity(productSpuBo);
        boolean save = productSpuService.save(productSpu);
        if (!save) {
            throw new BusinessException(ResultCodeEnums.BUSINESS_ERROR, "保存商品SPU失败");
        }
        log.info("保存商品SPU成功，ID：{}", productSpu.getId());
        // 调用下一个处理器
        if (Objects.nonNull(nextHandler)) {
            nextHandler.handler(productSpuBo);
        }
    }

    @Override
    public void setNextHandler(ProductSpuHandler nextHandler) {
        this.nextHandler = nextHandler;
    }

    @Override
    public ProductSpuHandler getNextHandler() {
        return this.nextHandler;
    }
}


